package com.zzyl.nursing.service.impl;

import java.time.format.DateTimeFormatter;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.ElderAddDto;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IContractService;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.vo.ElderBindedVo;
import com.zzyl.nursing.vo.FamilyMemberAndElderVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 客户老人关联Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-20
 */
@Service
public class FamilyMemberElderServiceImpl extends ServiceImpl<FamilyMemberElderMapper,FamilyMemberElder> implements IFamilyMemberElderService {
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    IElderService elderService;

    @Autowired
    IContractService contractService;

    @Autowired
    IFamilyMemberService familyMemberService;

    /**
     * 查询客户老人关联
     *
     * @param id 客户老人关联主键
     * @return 客户老人关联
     */
    @Override
    public FamilyMemberElder selectFamilyMemberElderById(Long id) {
                return getById(id);
    }

    /**
     * 查询客户老人关联列表
     *
     * @param familyMemberElder 客户老人关联
     * @return 客户老人关联
     */
    @Override
    public List<FamilyMemberElder> selectFamilyMemberElderList(FamilyMemberElder familyMemberElder) {
        return familyMemberElderMapper.selectFamilyMemberElderList(familyMemberElder);
    }

    /**
     * 新增客户老人关联
     *
     * @param elderAddDto 客户老人关联
     * @return 结果
     */
    @Override
    public boolean insertFamilyMemberElder(ElderAddDto elderAddDto) {
        //只要当前业务层的方法和controller的调用在一个线程内，即此处没有单独开启一个线程，就可以这样获取到service.
        // 获取当前请求的 HttpServletRequest
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        //此处需要获取family_member_id

        //判断是否签订合同，是否重复绑定？
        //先获取老人对象
        Elder elder= elderService.selectElderByIdCard(elderAddDto.getIdCard());
        //判断老人是否签订了合同
        Contract contract =contractService.lambdaQuery().eq(Contract::getElderId,elder.getId()).one();
        if(contract==null){
            //已经签了合同。
            //抛出异常
            throw new BaseException("该老人" + elder.getName() + "尚未签订合同。");
        }
        if(contract.getStatus()==0){
            //已经签了合同。
            //抛出异常
            throw new BaseException("该老人" + elder.getName() + "签订了合同，但尚未生效。"+ contract.getStartDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
        //生命绑定该变量
        FamilyMemberElder familyMemberElder=null;
        //判断该老人是否已经绑定过了。
        familyMemberElder=lambdaQuery().eq(FamilyMemberElder::getElderId,elder.getId()).one();
        Long userId= UserThreadLocal.getUserId();
        if(familyMemberElder!=null){
            throw new BaseException("该老人" + elder.getName() + "已经帮绑定过了。"+ familyMemberService.selectFamilyMemberById(userId).getName());
        }

        //该老人没有绑定，依据userId获取，后台信息。
//        familyMemberElder = getOne(Wrappers.<FamilyMemberElder>lambdaQuery().
//        eq(FamilyMemberElder::getFamilyMemberId, userId));
//        if(familyMemberElder==null){
//            //首次，尚未有记录
//            familyMemberElder = new FamilyMemberElder();
//            familyMemberElder.setFamilyMemberId(userId);
//        }else{
//            //说明，要绑定新的老人了。
//        }
        //只要之前没有绑定过，都是新增。
        familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setElderId(elder.getId());
        familyMemberElder.setFamilyMemberId(userId);
        //保存
        return save(familyMemberElder);

    }

    /**
     * 修改客户老人关联
     *
     * @param familyMemberElder 客户老人关联
     * @return 结果
     */
    @Override
    public int updateFamilyMemberElder(FamilyMemberElder familyMemberElder) {
                                                        return updateById(familyMemberElder) ? 1 : 0;
    }

    /**
     * 批量删除客户老人关联
     *
     * @param ids 需要删除的客户老人关联主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberElderByIds(Long[] ids) {
                return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除客户老人关联信息
     *
     * @param id 客户老人关联主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberElderById(Long id) {
                return removeById(id) ? 1 : 0;
    }

    /**
     * 在Controller层使用startPage()进行拦截
     *
     * @return
     */
    @Override
    public List<ElderBindedVo> listAll() {
        return familyMemberElderMapper.selectByMid(UserThreadLocal.get());
    }

    /**
     * 列出家属和老人的简要信息
     *
     * @return
     */
    @Override
    public List<FamilyMemberAndElderVo> listBriefInfo() {
        List<FamilyMemberAndElderVo> list = familyMemberElderMapper.selectBriefInfoByMid(UserThreadLocal.get());
        return list;
    }
}
